﻿using System;
using System.IO;
using System.Windows;
using zTalk.Network;
using System.Windows.Forms;
using System.Windows.Threading;

namespace zTalk
{
    public partial class FileTransfer : Window
    {
        //public string FileName { get; set; }
        public FileProto FileInfo { get; set; }
        public UserItem User { get; set; }
        public bool SendMode { get; set; }

        private string saveFileName;

        public FileTransfer()
        {
            InitializeComponent();
            SendMode = true;

            App.Handler.FileAccept += new PacketEventHandler(Handler_FileAccept);
            App.Handler.FileTransfer += new PacketEventHandler(Handler_FileTransfer);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (SendMode == true)
            {
                FileProto proto = new FileProto
                {
                    Source = App.User.Username,
                    Destination = User.Username,
                    FileName = FileInfo.FileName,
                    Size = FileInfo.Size,
                };
                Packet packet = Packet.Create(
                    Opcodes.FILE_SEND,
                    Json.Encode<FileProto>(proto)
                );
                App.Client.SendPacket(packet);
            }
            else
            {
                btnAccept.Visibility = Visibility.Visible;
                btnDecline.Visibility = Visibility.Visible;
                
            }
            lblInfo.Content = string.Format("{0} - {1} bytes", 
                Path.GetFileName(FileInfo.FileName), FileInfo.Size);
        }

        // ============ SENDER

        void Handler_FileAccept(object sender, PacketEventArgs ea)
        {
            FileProto proto = (FileProto)ea.Result;

            if (proto.Size != 0)
            {
                FileStream stream = new FileStream(FileInfo.FileName, FileMode.Open);
                BinaryReader reader = new BinaryReader(stream);

                byte[] buffer = new byte[FileInfo.Size];
                reader.Read(buffer, 0, FileInfo.Size);

                reader.Close();
                stream.Close();

                MessageProto message = new MessageProto
                {
                    Source = App.User.Username,
                    Destination = User.Username,
                    Time = "na",
                    Text = Convert.ToBase64String(buffer)
                };

                Packet packet = Packet.Create(
                    Opcodes.FILE_TRANSFER,
                    Json.Encode<MessageProto>(message)
                );
                App.Client.SendPacket(packet);
            }
            else
            {
                System.Windows.MessageBox.Show("Declined");
            }
        }

        // ============ RECEIVER

        void Handler_FileTransfer(object sender, PacketEventArgs ea)
        {
            MessageProto message = (MessageProto)ea.Result;

            byte[] buffer = Convert.FromBase64String(message.Text);

            FileStream fs = new FileStream(saveFileName, FileMode.Create);
            fs.Write(buffer, 0, buffer.Length);
            fs.Close();

            Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate {
                btnOpenFile.Visibility = Visibility.Visible;
                btnOpenFolder.Visibility = Visibility.Visible;
            }));
        }

        private void btnAccept_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = Path.GetFileName(FileInfo.FileName);
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                saveFileName = sfd.FileName;
                doAccept(true);
            }
        }

        private void btnDecline_Click(object sender, RoutedEventArgs e)
        {
            doAccept(false);
        }

        private void doAccept(bool accept)
        {
            FileProto reply = new FileProto
            {
                Destination = User.Username,
                Source = App.User.Username,
                FileName = FileInfo.FileName,
                Size = (accept == true) ? 1 : 0,
            };

            Packet packet = Packet.Create(
                Opcodes.FILE_ACCEPT,
                Json.Encode<FileProto>(reply)
            );
            App.Client.SendPacket(packet);
        }

        private void btnOpenFile_Click(object sender, RoutedEventArgs e)
        {
            /*System.Diagnostics.Process.Start(
                new System.Diagnostics.ProcessStartInfo(FileInfo.FileName));*/
        }

        private void btnOpenFolder_Click(object sender, RoutedEventArgs e)
        {
            /*System.Diagnostics.Process.Start(
                new System.Diagnostics.ProcessStartInfo(
                    Path.GetDirectoryName(FileInfo.FileName)));*/
        }
    }
}
